//
//  EFTagButton.m
//  ESPMobileView
//
//  Created by 虎 谢 on 2018/11/30.
//  Copyright © 2017年 Pansoft. All rights reserved.
//


#import "BlockStyleHorizontalMenu.h"
#import "EFMessageService.h"
#import "Constant.h"
#import "EnvironmentVariable.h"
#import "EFTagButton.h"
#import "Masonry.h"
#import "ViewControllerManager.h"
#import "MobileMainViewController.h"
#import "JFLanguageManager.h"
#import "CategoryHeader.h"

#define MENU_HEIGHT 44
#define TITLE_FONT  16.f
#define SELECT_TITLE_FONT 18.f
#define MAX_TITLEVIEW_WIDTH SCREEN_WIDTH - 120

@interface BlockStyleHorizontalMenu()

/// 可滑动标题View
@property (strong, nonatomic) UIScrollView *scrollView;
/// 按钮数组
@property (strong, nonatomic) NSMutableArray *buttons;
/// 标题数据
@property (strong, nonatomic) NSMutableArray *items;

@property(nonatomic,assign)   CGFloat scrollWidth;

@property(nonatomic,assign)   BOOL    isCenter;

@end

@implementation BlockStyleHorizontalMenu {
    NSMutableArray *_buttonArray;
}

-(instancetype)initWithFrame:(CGRect)frame items:(NSMutableArray *)items {
    self = [super initWithFrame:frame];
    if(self) {
        //点击进入聊天列表之后二级菜单的同步
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(unreadcountRefresh:) name:unreadcountChange
                                                   object:nil];
        
        //收到消息之后的监听
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(unreadcountRefresh:) name:@"chatCountChange"
                                                   object:nil];
        //任务列表数据改变之后的二级菜单的同步
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(taskUnreadRefresh:) name:@"taskUnreadcountChange"
                                                   object:nil];
        
        //通讯录数据改变之后的二级菜单的同步(新的朋友，群通知)
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(chatAddressBookAction) name:@"chatAddressCountChange"
                                                   object:nil];
        
        
        self.items = items;
        self.fontSize = TITLE_FONT;
        self.selectFontSize = SELECT_TITLE_FONT;
        self.titleColor = RGBA(255, 255, 255,1);
        self.selectedTitleColor = [UIColor redColor];
        _buttonArray = [NSMutableArray array];
        [self creationComplete];
    }
    return self;
}

- (void)setThemeWithStub:(StubObject *)stub{
    //是否居中显示item
    self.isCenter = [[stub getStringForKey:@"isCenter" withDefaultValue:@"YES"] boolValue];

    NSString *bsColorString = [stub getStringForKey:@"bsColor" withDefaultValue:@""];
    NSArray *bsColors = [bsColorString componentsSeparatedByString:@","];
    if (bsColorString && bsColors && bsColors.count == 2) {
        self.titleColor = [UIColor colorWithHexString:bsColors[0]];
        self.selectedTitleColor = [UIColor colorWithHexString:bsColors[1]];
    } else {
        self.titleColor =RGBA(255, 255, 255, 1);
        self.selectedTitleColor =RGBA(255, 0, 0, 1);
    }
    
    NSString *bsFontString = [stub getStringForKey:@"bsFont" withDefaultValue:@""];
    NSArray *bsFonts = [bsFontString componentsSeparatedByString:@","];
    if (bsFontString && bsFonts && bsFonts.count == 2) {
        self.fontSize = [bsFonts[0] doubleValue];
        self.selectFontSize = [bsFonts[1] doubleValue];;
    } else {
        self.fontSize = 16.f;
        self.selectFontSize = 18.f;
    }
 
    [self creationComplete];
}

-(void)changeButtonTitle:(NSString *)title index:(NSInteger)index {
    if(_buttonArray.count < index)  return;
    EFTagButton *button = [_buttonArray objectAtIndex:index];
    button.userInteractionEnabled = NO;
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
}

#pragma mark - 布局标题栏
- (void)creationComplete{
    /// 移除旧的标题栏
    for (UIView *subView in self.scrollView.subviews) {
        if ([subView isKindOfClass:[EFTagButton class]]) {
            [subView removeFromSuperview];
        }
    }
    self.scrollWidth = 0;
    [self.buttons removeAllObjects];
    [_buttonArray removeAllObjects];
    /// 往ScrollView上面添加标题
    [self.items enumerateObjectsUsingBlock:^(StubObject *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView *lastView;
        if (self.buttons.count > 0) {
            lastView = self.buttons.lastObject;
        }
//        NSString *title = [obj getCaption];
        NSString *title = [JFLanguageManager titleWithStubobject:obj];
        EFTagButton *button = [EFTagButton buttonWithType:UIButtonTypeCustom];
        [_buttonArray addObject:button];
        [button.titleLabel setFont:[UIFont systemFontOfSize:self.fontSize]];
        button.titleLabel.textAlignment = NSTextAlignmentCenter;
        button.stub = obj;
        [button setTitle:title forState:UIControlStateNormal];
        if (self.items.count == 1) {
            [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        }else {
            [button setTitleColor:self.titleColor forState:UIControlStateNormal];
        }
        button.tag = idx + 1000;
        /// 按钮文字宽度
        CGFloat buttonTitleWidth = [title boundingRectWithSize:CGSizeMake(SCREEN_WIDTH, MENU_HEIGHT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:self.fontSize]} context:nil].size.width + 25;
        [self.scrollView addSubview:button];
        [self.buttons addObject:button];
        self.scrollWidth = self.scrollWidth + buttonTitleWidth;
        [button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.centerY.equalTo(self.scrollView);
            make.height.mas_equalTo(MENU_HEIGHT);
            make.width.mas_equalTo(buttonTitleWidth);
            if (lastView) {
                make.left.equalTo(lastView.mas_right);
            }else{
                make.left.equalTo(self.scrollView);
            }
            if (idx == self.items.count - 1) {
                make.right.equalTo(self.scrollView);
            }
        }];
        
        if (self.items.count>1) {
            button.tagView.badgeValue = [self unreadCountWithStubobject:obj];
            [self chatAddressBookAction];
            [button addTarget:self action:@selector(actionbtn:) forControlEvents:UIControlEventTouchUpInside];
            //将关联apply的cell添加到EFMessageService的ViewMap中
            if ([obj getStringForKey:@"applyId" withDefaultValue:nil]) {
                NSMutableArray *sonArray = [[NSMutableArray alloc]init];
                if ([[EFMessageService sharedMessageService].viewMap objectForKey:[obj getStringForKey:@"applyId" withDefaultValue:nil]]) {
                    sonArray = [[EFMessageService sharedMessageService].viewMap objectForKey:[obj getStringForKey:@"applyId" withDefaultValue:nil]];
                }
                [sonArray addObject:button];
                [[EFMessageService sharedMessageService].viewMap setObject:sonArray forKey:[obj getStringForKey:@"applyId" withDefaultValue:nil]];
            }
        }
    }];
    
    [self.scrollView layoutIfNeeded];
   
    [self configViews];
    
    if (self.items.count >= 1) {
        [self scrollWithScrollScale:0];
    }
}

-(void)configViews {
    //设置scrolview的布局
    if (self.isCenter) {
        [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.bottom.equalTo(self);
            make.centerX.equalTo(self);
            make.width.mas_equalTo(self.scrollWidth);
        }];
    }else {
        [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self);
            make.height.mas_equalTo(MENU_HEIGHT);
            make.width.mas_equalTo(MAX_TITLEVIEW_WIDTH);
        }];
    }
}

#pragma mark - 监听未读消息数
-(NSString *)unreadCountWithStubobject:(StubObject *)stub {
    //XML上配置的一些APPLYID总共的未读数目
    NSArray  *appArray = [[stub getStringForKey:@"applyId" withDefaultValue:nil] componentsSeparatedByString:@";"];
    NSInteger applyCount = 0;
    if (appArray) {
        //根据EFMessageService的menuMap 赋值badgevalue
        for (NSString *applyID in appArray) {
            applyCount += [[[EFMessageService sharedMessageService].menuMap objectForKey:applyID] integerValue];
        }
    }
    //特殊处理的一些未读数目
    NSInteger listCount = 0;
    if ([[stub.stubTable objectForKey:@"show"] isEqualToString:@"EFChatListViewController"]) {
        //是聊天列表
        listCount = [[EnvironmentVariable getPropertyForKey:@"EFChatListViewController" WithDefaultValue:@"0"] integerValue];
        
        if ((listCount + applyCount)>99) {
            return @"99+";
        }
        return [NSString stringWithFormat:@"%ld",listCount+applyCount];
        
    }else if([[stub.stubTable objectForKey:@"show"] isEqualToString:@"EFTaskListViewController"]){
        listCount = [[EnvironmentVariable getPropertyForKey:@"EFTaskListViewController" WithDefaultValue:@"0"] integerValue];
        if ((listCount + applyCount)>99) {
            return @"99+";
        }
        return [NSString stringWithFormat:@"%ld",listCount+applyCount];
    }else {
        return [NSString stringWithFormat:@"%ld",applyCount];
    }
    return @"0";
}

//是否应用号消息
- (BOOL)isApplyAction:(NSString *)userIdStr{
    if ([[EFMessageService sharedMessageService].menuMap objectForKey:userIdStr]) {
        return YES;
    }
    return NO;
}

-(void)unreadcountRefresh:(NSNotification *)note {
    NSMutableArray *chatListArray = [[NSMutableArray alloc]init];
    chatListArray  = [EFMessageService sharedMessageService].listArray;
    NSInteger badgeValue = 0;
    for (EFChatListModel *model in chatListArray) {
        BOOL isBother = model.isBother;
        if (!model.isBother) {
            BOOL isApply = [self isApplyAction:[NSString stringWithFormat:@"%d",model.message.fromUserID]];
            if (!isApply) {
                badgeValue = badgeValue + [[JFMessageManager sharedMessageManager] unreadCountWithUserID:model.userId postType:[model.type integerValue]];
                [model.badgerNum integerValue];
            }
        }
    }
    [EnvironmentVariable setProperty:[NSString stringWithFormat:@"%ld",badgeValue] forKey:@"EFChatListViewController"];
    //TODO:处理
    for (EFTagButton *item in _buttons) {
        if (item.isShow) {
            NSString *showName = [item.stub getStringForKey:@"show" withDefaultValue:nil];
            if ([showName isEqualToString:note.object]) {
                if ([[EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"] integerValue]>99) {
                    item.tagView.badgeValue = @"99+";
                }else {
                    item.tagView.badgeValue = [EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"];
                }
            }
        }
    }
}

-(void)chatAddressBookAction{
    NSString *NewFr = [EnvironmentVariable getPropertyForKey:@"newFriendBadgeValue" WithDefaultValue:@"0"];
    NSString *NewJoin = [EnvironmentVariable getPropertyForKey:@"newJoinGroupBadgeValue" WithDefaultValue:@"0"];
    NSInteger N = [NewFr integerValue] + [NewJoin integerValue];
    for (EFTagButton *item in _buttons) {
        NSString *showName = [item.stub getStringForKey:@"show" withDefaultValue:nil];
        if ([showName isEqualToString:@"ChatAddressBookViewController"]) {
            item.tagView.badgeValue = [NSString stringWithFormat:@"%ld",N];
        }
    }
}

-(void)taskUnreadRefresh:(NSNotification *)note {
    for (EFTagButton *item in _buttons) {
        NSString *showName = [item.stub getStringForKey:@"show" withDefaultValue:nil];
        if ([showName isEqualToString:note.object]) {
            if ([[EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"] integerValue]>99) {
                item.tagView.badgeValue = @"99+";
            }else {
                item.tagView.badgeValue = [EnvironmentVariable getPropertyForKey:showName WithDefaultValue:@"0"];
            }
            
        }
    }
}
#pragma mark - button按钮点击事件
- (void)actionbtn:(UIButton *)button {
    [self changeButtonState:button];
    //调用delegate
    if (self.delegate!= nil && [_delegate respondsToSelector:@selector(blockStyleHorizontalMenu:didClickItem:position:)]) {
        [self.delegate blockStyleHorizontalMenu:self didClickItem:[self.items objectAtIndex:button.tag-1000] position:(int)button.tag-1000];
    }
}
#pragma mark - 修改选中按钮
-(void)changeButtonState:(UIButton *)button{
    [self.scrollView layoutIfNeeded];
    
//    WEAK(self)
    [UIView animateWithDuration:0.2 animations:^{
        /// 2.设置选中按钮的颜色改变
        for (UIButton *btn in self.buttons) {
            UIColor *color = [button isEqual:btn]?self.selectedTitleColor:self.titleColor;
            btn.titleLabel.font = [UIFont systemFontOfSize:[button isEqual:btn]?self.selectFontSize:self.fontSize];
            [btn setTitleColor:color forState:UIControlStateNormal];
        }
        
        /// 3.自动滑动TitleScroll
        CGFloat width = self.scrollView.contentSize.width;
        if (width > MAX_TITLEVIEW_WIDTH) {
            CGFloat btnCenterX = button.center.x;
            CGFloat headerScrollWidth = self.scrollView.bounds.size.width;
            if (btnCenterX > headerScrollWidth/2 && (self.scrollView.contentSize.width - btnCenterX) > headerScrollWidth/2) {
                /// 中间状态需让背后的ScrollView也滚动
                self.scrollView.contentOffset = CGPointMake(btnCenterX - headerScrollWidth/2, 0);
            }else if (btnCenterX < headerScrollWidth/2){
                /// scrollView维持在最左边
                self.scrollView.contentOffset = CGPointMake(0, 0);
            }else if ((self.scrollView.contentSize.width - btnCenterX) < headerScrollWidth/2){
                /// scrollView维持在最右边
                self.scrollView.contentOffset = CGPointMake(self.scrollView.contentSize.width-headerScrollWidth, 0);
            }
        }
        [self layoutIfNeeded];
    }];

}

#pragma mark - 根据下标滑动标题栏
-(void)selectMenuAtIndex:(int)index {
    [self changeButtonState:self.buttons[index]];
}

#pragma mark - 根据偏移滑动标题栏
- (void)scrollWithScrollScale:(CGFloat)scrollScale{
    /// 上一个按钮的index
    NSUInteger lastButtonIndex = (NSUInteger)scrollScale;
    /// 从上一个按钮到下一个按钮走过的比例
    CGFloat lastButtonToNextButtonScale = scrollScale - lastButtonIndex;
    
    UIButton *lastButton = self.buttons[lastButtonIndex];
    
    UIColor *lastColor = [self getColorWithColor:self.selectedTitleColor endColor:self.titleColor andCoe:(double)lastButtonToNextButtonScale];
    UIColor *nextColor = [self getColorWithColor:self.titleColor endColor:self.selectedTitleColor  andCoe:(double)lastButtonToNextButtonScale];
    
//    NSLog(@"%f",lastButtonToNextButtonScale);

    /// 修改标题颜色根据滑动渐变
    [lastButton setTitleColor:lastColor forState:UIControlStateNormal];
    
    CGFloat fontScale = (self.selectFontSize - self.fontSize);
    lastButton.titleLabel.font = [UIFont systemFontOfSize:self.fontSize+fontScale*(1-lastButtonToNextButtonScale)];
    
    
    if (lastButtonIndex < self.items.count-1) {
        UIButton *nextButton = self.buttons[lastButtonIndex+1];
        
        [nextButton setTitleColor:nextColor forState:UIControlStateNormal];
        nextButton.titleLabel.font = [UIFont systemFontOfSize:self.fontSize+fontScale*lastButtonToNextButtonScale];
        
        /// 标题栏宽
        CGFloat titleScrollWidth = self.scrollView.frame.size.width;
        /// 标题栏内容宽
        CGFloat titleScrollContentWidth = self.scrollView.contentSize.width;
        
        /// 自动滑动TitleScroll
        if (titleScrollContentWidth > MAX_TITLEVIEW_WIDTH) {
            /// 整个需要滑动的比例
            CGFloat needScrollScale = scrollScale / self.items.count;
            /// 整个需要滑动的距离
            CGFloat needScrollWidth = needScrollScale * titleScrollContentWidth;
            
            if (needScrollWidth > titleScrollWidth/2 && (titleScrollContentWidth - needScrollWidth) > titleScrollWidth/2) {
                /// 中间状态需让背后的ScrollView也滚动
                self.scrollView.contentOffset = CGPointMake(needScrollWidth - titleScrollWidth/2, 0);
            }else if (needScrollWidth < titleScrollWidth/2){
                /// scrollView维持在最左边
                self.scrollView.contentOffset = CGPointMake(0, 0);
            }else if ((titleScrollContentWidth - needScrollWidth) < titleScrollWidth/2){
                /// scrollView维持在最右边
                self.scrollView.contentOffset = CGPointMake(titleScrollContentWidth-titleScrollWidth, 0);
            }
        }
    }
}

#pragma mark - 添加条目
-(void)addItemForArray:(StubObject *)item{
    [self.items addObject:item];
}

#pragma mark - 重置items
-(void)resetViewItems:(NSMutableArray *)items{
    self.items = items;
    [self creationComplete];
}


#pragma mark - 平滑颜色变换
/// 获取颜色rgb
- (NSArray *)getRGBDictionaryByColor:(UIColor *)originColor{
    CGFloat r=0,g=0,b=0,a=0;
    if ([self respondsToSelector:@selector(getRed:green:blue:alpha:)]) {
        [originColor getRed:&r green:&g blue:&b alpha:&a];
    }else {
        const CGFloat *components = CGColorGetComponents(originColor.CGColor);
        r = components[0];
        g = components[1];
        b = components[2];
        a = components[3];
    }
    
    return @[@(r*255),@(g*255),@(b*255)];
}

/// 计算开始颜色和结束颜色的颜色差
- (NSArray *)transColorBeginColor:(UIColor *)beginColor andEndColor:(UIColor *)endColor {
    NSArray<NSNumber *> *beginColorArr = [self getRGBDictionaryByColor:beginColor];
    NSArray<NSNumber *> *endColorArr = [self getRGBDictionaryByColor:endColor];
    return @[@([endColorArr[0] doubleValue] - [beginColorArr[0] doubleValue]),@([endColorArr[1] doubleValue] - [beginColorArr[1] doubleValue]),@([endColorArr[2] doubleValue] - [beginColorArr[2] doubleValue])];
}

/// 获取渐变颜色
- (UIColor *)getColorWithColor:(UIColor *)beginColor endColor:(UIColor *)endColor andCoe:(double)coe{
    NSArray *beginColorArr = [self getRGBDictionaryByColor:beginColor];
    NSArray *toEndScaleColorArr = [self transColorBeginColor:beginColor andEndColor:endColor];
    double red = [beginColorArr[0] doubleValue] + coe * [toEndScaleColorArr[0] doubleValue];
    double green = [beginColorArr[1] doubleValue]+ coe * [toEndScaleColorArr[1] doubleValue];
    double blue = [beginColorArr[2] doubleValue] + coe * [toEndScaleColorArr[2] doubleValue];
    return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:1];
}


#pragma mark - lazyload
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_scrollView];
//        [_scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.edges.equalTo(self);
//            make.height.mas_equalTo(MENU_HEIGHT);
//            make.width.mas_equalTo(0);
//        }];
    }
    return _scrollView;
}

- (NSMutableArray *)buttons{
    if (!_buttons) {
        _buttons = [NSMutableArray array];
    }
    return _buttons;
}
- (NSMutableArray *)items{
    if (!_items) {
        _items = [NSMutableArray array];
    }
    return _items;
}
@end
